package at.fhj.swd.pse.beans;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.ejb.Stateless;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.codec.binary.Hex;

import at.fhj.swd.pse.entities.User;
import at.fhj.swd.pse.helper.UserManager;

@Named
@Stateless
@ManagedBean
public class LoginBean {

	@PersistenceContext
	private EntityManager em;

	@Inject
	private UserManager userManager;

	private String username;
	private String password;

	public LoginBean() {
		// TODO Auto-generated constructor stub
	}

	public String getUsername() {
		return this.username;
	}

	public void setUsername(final String username) {
		this.username = username;
	}

	public String getPassword() {
		return this.password;
	}

	public void setPassword(final String password) {
		this.password = password;
	}

	public String login() {
		FacesContext context = FacesContext.getCurrentInstance();

		String pwdHash = null;
		try {
			pwdHash = CalcHash(this.password);
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
			context.addMessage(null, new FacesMessage("Login failed: " + e.getMessage()));
			return "";
		}

		Query q = this.em.createQuery("select u from User u where u.username=:username and u.password=:password");
		q.setParameter("username", this.username);
		q.setParameter("password", pwdHash);

		try {
			User currentUser = (User) q.getSingleResult();
			this.userManager.setActiveUser(currentUser);
		} catch (NoResultException ex) {
			context.addMessage(null, new FacesMessage("Login failed."));
			return "";
		}

		return "index";
	}

	public void logout() {
		// FacesContext context = FacesContext.getCurrentInstance();
		// Logout -> I am default user
		// context.addMessage(null, new FacesMessage("Logout failed."));
	}

	private static String CalcHash(final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		if (password == null) {
			return null;
		}

		MessageDigest cript = MessageDigest.getInstance("SHA-1");
		cript.reset();
		cript.update(password.getBytes("utf8"));
		return new String(Hex.encodeHex(cript.digest()));
	}
}
